<template>
    <Modal
        v-model="isVisible"
        title="更改管理者">

        <Form :label-width="80" style="padding-right:20px;">
	        <FormItem label="已选房源">
                <Tag>
                    {{homeName}}
                </Tag>
            </FormItem>
			
			<FormItem label="房源归属">
                <!-- 这个选项不影响接口字段,产品作为区分总部来使用 -->
                <Select
                    v-model="formInline.roomInfo"
                    @on-change="handleParentChange"
                    placeholder="选择分店">
                    <Option :value="1">总部</Option>
                    <Option :value="2">分店</Option>
                </Select>
            </FormItem>

            <FormItem label="所选门店" placeholder="选择门店">
                <Select
                	v-model="formInline.shopInfo"
                	:disabled="formInline.roomInfo === 1"
                	@on-change="handleFetchKeeper">
			        <Option v-for="item in shopList" :value="item.id" :key="item.id">{{ item.name }}</Option>
			    </Select>
            </FormItem>

            <FormItem label="管家">
				<Select
					filterable
                    multiple
                    v-model="formInline.managerInfo"
                    placeholder="选择管家">
			        <Option v-for="item in managerList" :value="item.id" :key="item.id">{{ item.name }}</Option>
			    </Select>
            </FormItem>
	    </Form>

	    <div slot="footer">
            <Button type="ghost" size="large" @click="hideModal">取消</Button>
            <Button
            	type="ghost"
            	size="large"
            	@click="subInfo"
            	:loading="loading">提交</Button>
        </div>

    </Modal>
</template>

<script>
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
export default {
  name: 'editManager',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    homeName: {
      // 房源编号
      type: String
    },
    branchId: {
      // 获取管家列表所需参数
      type: Number
    },
    id: {
      // 房间id
      type: Number
    }
  },
  data () {
    return {
      formInline: {
        roomInfo: 1,
        branchId: null,
        shopInfo: '总部', // 选中门店
        managerInfo: [] // 选中管家
      },
      loading: false,
      shopList: [], // 门店列表
      managerList: [] // 管家列表
    }
  },
  mounted () {
    this.formInline.branchId = this.branchId
    this.initManager()
    this.getbranches()
  },
  computed: {
    isVisible: {
      get: function () {
        return this.visible
      },

      set: function () {
        this.$emit('on-close')
      }
    }
  },
  methods: {
    /**
         * 更改门店, 管家
         * 如果不选择管家, 调用更改门店接口
         */
    subInfo () {
      this.loading = true
      if (this.formInline.roomInfo === 1) {
        // 所属门店为 "总部" ，无所选门店，满足不选择管家条件即可
        if (this.formInline.managerInfo.length === 0) {
          this.changeBranch()
          return
        }
      } else {
        // 所属门店为 "分店" ，必须选择门店，同时满足不选择管家条件
        if (this.formInline.managerInfo.length === 0 && this.formInline.shopInfo) {
          this.changeBranch()
          return
        }
      }

      if (this.formInline.roomInfo === 2 && !this.formInline.shopInfo) {
        this.loading = false
        return this.$Message.warning('请选择门店')
      }

      const data = {
        home_ids: [this.id],
        branch_id: this.formInline.branchId,
        user_ids: this.formInline.managerInfo
      }

      http.request(this, api.home_users, null, data, (res, err) => {
        if (err || !res) {
          this.$Message.error(err.data.err_msg)
        } else {
          this.refreshParent()
          this.$Message.success('操作成功')
          this.cleanModalAfterChange()
        }
        this.isVisible = false
        this.loading = false
      })
    },

    hideModal () {
      this.isVisible = false
    },

    changeBranch () {
      const data = {
        home_ids: [this.id],
        branch_id: this.formInline.branchId
      }
      http.request(this, api.home_update_brance, null, data, (res, err) => {
        if (err || !res) {
          this.$Message.error(err.data.err_msg)
        } else {
          this.refreshParent()
          this.$Message.success('操作成功')
          this.cleanModalAfterChange()
        }
        this.isVisible = false
        this.loading = false
      })
    },

    refreshParent () {
      let shop = ''
      let manager = []
      for (let k = 0; k < this.shopList.length; k++) {
        if (this.formInline.shopInfo === this.shopList[k].id) {
          shop = this.shopList[k].name
          break
        }
      }
      for (let k = 0; k < this.managerList.length; k++) {
        for (let j = 0; j < this.formInline.managerInfo.length; j++) {
          if (this.managerList[k].id === this.formInline.managerInfo[j]) {
            manager.push({ name: this.managerList[k].name })
          }
        }
      }
      this.$emit('changeManagerSuc', { shop: shop, manager: manager })
    },

    cleanModalAfterChange () {
      this.formInline.roomInfo = 1
      this.formInline.shopInfo = ''
      this.formInline.managerInfo = []
    },

    initManager () {
      const query = {
        offset: 0,
        limit: 1000,
        role_id: 104,
        branch_id: this.formInline.branchId || null,
        list_type: 'all'
      }
      http.request(this, api.user_list, null, query, (res, err) => {
        if (err) {
          this.$Message.error('获取管家列表失败')
        } else {
          let datas = res && res.rows
          if (this.formInline.branchId === 0) {
            datas = datas.filter(item => item.branches.length === 0)
          }
          this.managerList = datas
        }
      })
      if (this.formInline.branchId !== 0) {
        this.formInline.roomInfo = 2
      }
    },

    // 获取门店
    getbranches () {
      dataCenter.getStores(this, (res, err) => {
        if (err || !res) {
          return
        }
        this.shopList = res
      })
    },

    handleParentChange (res) {
      this.formInline.shopInfo = 0
      this.formInline.branchId = 0
      this.formInline.managerInfo = []
      this.managerList = []
      if (res === 1) {
        this.handleFetchKeeper(0)
      }
    },

    handleFetchKeeper (id) {
      if (id === undefined) return
      this.formInline.managerInfo = []
      this.formInline.branchId = id
      const query = {
        offset: 0,
        limit: 100,
        role_id: 104,
        branch_id: id || null,
        list_type: 'all'
      }
      http.request(this, api.user_list, null, query, (res, err) => {
        if (err) {
          this.$Message.error('获取管家列表失败')
        } else {
          let datas = res && res.rows
          if (id === 0) {
            datas = datas.filter(item => item.branches.length === 0)
          }
          this.managerList = datas
        }
      })
    }
  }
}
</script>

<style scoped>
.title {
    text-align: right;
    padding-right: 20px;
}
.form-item {
    margin-bottom: 10px;
}
.ivu-form-item {
    margin-bottom: 18px;
}
</style>